<template>
  <render/>
</template>
<script setup>
import {useStore} from 'vuex';
import {useRoute, useRouter} from 'vue-router';
import {defineComponent, h, KeepAlive, nextTick, shallowRef} from 'vue';
import {guid} from '@utils';

defineOptions({
  name: 'HKeepAlive'
});
const router = useRouter();
const route = useRoute();
const props = defineProps({
  config: {
    type: Object,
    default: ({})
  }
});
const realComponent = shallowRef(defineComponent({render: () => h('span')}));
const store = useStore();
const render = () => {
  nextTick(doRend);
  if (!props.config.Component || !realComponent) return [];
  return h(KeepAlive, {
    includs: store.getters.keepAlived,
    exclude: store.getters.exclude
  }, h(realComponent.value));
};

function genRealComponentKey(comp) {
  if (!comp?.type?.name) return `comp_${guid()}`;
  return `${comp?.type?.name}_${route.fullPath}`;
}

function clearCachedComponent(componentName, callback) {
  store.commit('runtime/removeKeepAlive', componentName);
  nextTick(() => {
    store.commit('runtime/clearKeepAlive');
    nextTick(() => {
      store.commit('runtime/addKeepAlive', componentName);
      callback();
    });
  });
}

function doRend() {
  let componentName = props.config?.Component?.type?.name;
  if (props.config?.Component?.type?.name) {
    if (realComponent.value === props.config?.Component) return;
    store.commit('runtime/addKeepAlive', componentName);
  }

  if (store.getters.needRefresh) {
    console.log('需要下一个页面清空缓存', componentName);
    //需要下一个页面清空缓存
    clearCachedComponent(componentName, () => {
      rendRealComponent();
      store.commit('runtime/setReresh', false);
    });
  } else {
    rendRealComponent();
  }
}

function rendRealComponent() {
  nextTick(() => {
    if (props.config.Component) {
      // console.log(realComponent.value?.type?.name === props.config.Component?.type?.name)
      if (realComponent.value === props.config.Component) {
      } else {
        // console.log('路由切换了组件')
        realComponent.value = props.config.Component;
      }
    }
  });
}

</script>